package com.dragonboat.controller;
import com.dragonboat.util.PasswordUtil;
import com.dragonboat.entity.Event;
import com.dragonboat.entity.Registration;
import com.dragonboat.entity.Team;
import com.dragonboat.repository.OrganizerRepository;
import com.dragonboat.service.TeamService;
import com.dragonboat.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
import java.util.List;
import com.dragonboat.repository.TeamRepository;
@RestController
@RequestMapping("/team")
public class TeamController {
    @Autowired
    private TeamService teamService;
    @Autowired
    private TeamRepository teamRepository;
    @PostMapping("/register")
    public ResponseResult<Team> register(@RequestBody Map<String, String> request) {
        String teamName = request.get("teamName");
        String password = request.get("password");

        if (teamRepository.existsByTeamName(teamName)) {
            return ResponseResult.error("队伍名称已存在");
        }

        Team team = new Team();
        team.setTeamName(teamName);
        team.setPassword(PasswordUtil.encode(password)); // 使用哈希密码

        teamRepository.save(team);
        team.setPassword(null); // 不返回密码

        return ResponseResult.success(team);
    }



    @PostMapping("/login")
    public ResponseResult<Team> login(@RequestParam Integer teamId,
                                      @RequestParam String password) {
        return teamService.login(teamId, password)
                .map(team -> {
                    team.setPassword(null); // 不返回密码
                    return ResponseResult.success(team);
                })
                .orElse(ResponseResult.error("Login failed"));
    }
    @GetMapping("/findById/{teamId}")
    public ResponseResult<Team> findById(@PathVariable Integer teamId) {
        Team team = teamService.getTeamById(teamId);
        if (team != null) {
            team.setPassword(null); // 不返回密码
            return ResponseResult.success(team);
        }
        return ResponseResult.error("Team not found");
    }
    @PostMapping("/loginByname")
    public ResponseResult<Team> loginByName(@RequestParam String teamName,
                                            @RequestParam String password) {
        return teamRepository.findByTeamName(teamName)
                .filter(t -> PasswordUtil.matches(password, t.getPassword()))
                .map(team -> {
                    team.setPassword(null);
                    return ResponseResult.success(team);
                })
                .orElseGet(() -> {
                    System.out.println("Login failed - teamName: " + teamName + ", password: " + password); // 添加控制台输出
                    return ResponseResult.error("Login failed");
                });
    }

    @GetMapping("/getAvailableEvents/{teamId}")
    public ResponseResult<List<Event>> getAvailableEvents(@PathVariable Integer teamId) {
        return ResponseResult.success(teamService.getAvailableEventsForTeam(teamId));
    }

    @PostMapping("/event/{eventId}/register")
    public ResponseResult<Registration> registerEvent(@PathVariable Integer eventId,
                                                      @RequestBody Map<String, Integer> request) {
        Integer teamId = request.get("teamId");
        try {
            Registration registration = teamService.registerEvent(eventId, teamId);
            return ResponseResult.success(registration);
        } catch (RuntimeException e) {
            return ResponseResult.error(400, e.getMessage());
        }
    }

    @DeleteMapping("/event/{eventId}/cancel")
    public ResponseResult<Boolean> cancelRegistration(@PathVariable Integer eventId,
                                                      @RequestParam Integer teamId) {
        try {
            boolean result = teamService.cancelRegistrationByEvent(eventId, teamId);
            return result ? ResponseResult.success(true)
                    : ResponseResult.error(400, "取消报名失败");
        } catch (RuntimeException e) {
            return ResponseResult.error(400, e.getMessage());
        }
    }

    @GetMapping("/registrations")
    public ResponseResult<List<Registration>> getRegistrations(@RequestParam Integer teamId) {
        List<Registration> registrations = teamService.getRegistrationsByTeam(teamId);
        return ResponseResult.success(registrations);
    }


    @GetMapping("/events")
    public ResponseResult<List<Event>> getAllEvents() {
        return ResponseResult.success(teamService.getAllEvents());
    }

    @PostMapping("/updateInfo")
    public ResponseResult<Team> updateInfo(@RequestParam Integer teamId,
                                           @RequestParam(required = false) String name,
                                           @RequestParam(required = false) String oldPassword,
                                           @RequestParam(required = false) String newPassword) {
        // 验证旧密码
        if (newPassword != null && !newPassword.isEmpty()) {
            Team team = teamService.getTeamById(teamId);
            if (team == null || !team.getPassword().equals(oldPassword)) {
                return ResponseResult.error("Old password is incorrect");
            }
        }
        return ResponseResult.success(teamService.updateTeamInfo(teamId, name, newPassword));
    }

}